<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\logging\writers;

#use \InvalidArgumentException;
#use tehframework\logging\LogWriter;

class FileLogWriter extends LogWriter
{
	const MODE_PREPEND = 'r+';
	const MODE_APPEND  = 'a';
	
	/**
	 * @var FileLogWriter::MODE_*
	 */
	private $mode;
	
	/**
	 * @var string
	 */
	private $path;
	
	/**
	 * @var resource?
	 */
	private $handle;
	
	/**
	 * @param  string $filePath
	 * @param  FileLogWriter::MODE_* $mode
	 * @throws InvalidArgumentException
	 */
	public function __construct($filePath, $mode = self::MODE_PREPEND)
	{
		$this->setFile($filePath, $mode);
	}
	
	/**
	 * @param  string $path
	 * @param  FileLogWriter::MODE_* $mode
	 * @return FileLogWriter
	 * @throws InvalidArgumentException
	 */
	public function setFile($path, $mode)
	{
		if (!file_exists($path) || !is_writable($path))
		{
			throw new InvalidArgumentException(sprintf(
				'[%s] does not exist or is not writable.', $path
			));
		}
		
		$this->path = $path;
		$this->mode = $mode === self::MODE_APPEND
			? self::MODE_APPEND : self::MODE_PREPEND;
		
		$this->handle = null;
		
		return $this;
	}
	
	/**
	 * @param  Log $log
	 * @return FileLogWriter
	 * @throws LoggingException
	 */
	public function writeLog(Log $log)
	{
		$fh = fopen($this->path, $this->mode);
		fwrite($fh, (string)$log . PHP_EOL);
		fclose($fh);
		
		return $this;
	}
	
	/**
	 * @param  array<Log> $logs
	 * @return FileLogWriter
	 * @throws LoggingException
	 */
	public function writeAllLogs(array $logs)
	{
		$fh = fopen($this->path, $this->mode);
		
		foreach ($logs as $log)
		{
			fwrite($fh, (string)$log . PHP_EOL);
		}
		
		fclose($fh);
		
		return $this;
	}
}